package com.yuanqi.service.impl;

import com.yuanqi.domain.User;
import com.yuanqi.repository.UserRepository;
import com.yuanqi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Optional;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserRepository userRepository;
    
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    
    @Override
    public User getUserById(Long id) {
        Optional<User> userOpt = userRepository.findById(id);
        return userOpt.orElse(null);
    }
    
    @Override
    public User getUserByUsername(String username) {
        Optional<User> userOpt = userRepository.findByUsername(username);
        return userOpt.orElse(null);
    }
    
    @Override
    public User updateUserProfile(Long userId, Map<String, Object> profileData) {
        User user = getUserById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 更新允许修改的字段
        if (profileData.containsKey("name")) {
            user.setName((String) profileData.get("name"));
        }
        if (profileData.containsKey("email")) {
            String email = (String) profileData.get("email");
            if (email != null && !email.isEmpty() && !isEmailAvailable(email, userId)) {
                throw new RuntimeException("邮箱已被使用");
            }
            user.setEmail(email);
        }
        if (profileData.containsKey("mobile")) {
            String mobile = (String) profileData.get("mobile");
            if (mobile != null && !mobile.isEmpty() && !isMobileAvailable(mobile, userId)) {
                throw new RuntimeException("手机号已被使用");
            }
            user.setMobile(mobile);
        }
        if (profileData.containsKey("bio")) {
            user.setBio((String) profileData.get("bio"));
        }
        if (profileData.containsKey("department")) {
            user.setDepartment((String) profileData.get("department"));
        }
        if (profileData.containsKey("position")) {
            user.setPosition((String) profileData.get("position"));
        }
        
        // 设置更新时间
        user.setUpdatedAt(LocalDateTime.now());
        user.setUpdatedBy(userId);
        
        return userRepository.save(user);
    }
    
    @Override
    public boolean changePassword(Long userId, String oldPassword, String newPassword) {
        User user = getUserById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 验证旧密码
        if (!verifyPassword(userId, oldPassword)) {
            throw new RuntimeException("旧密码不正确");
        }
        
        // 验证新密码强度
        if (newPassword == null || newPassword.length() < 6) {
            throw new RuntimeException("新密码长度不能少于6位");
        }
        
        // 加密新密码
        String encodedPassword = passwordEncoder.encode(newPassword);
        user.setPasswordHash(encodedPassword);
        user.setUpdatedAt(LocalDateTime.now());
        user.setUpdatedBy(userId);
        
        userRepository.save(user);
        return true;
    }
    
    @Override
    public boolean verifyPassword(Long userId, String password) {
        User user = getUserById(userId);
        if (user == null || password == null) {
            return false;
        }
        
        return passwordEncoder.matches(password, user.getPasswordHash());
    }
    
    @Override
    public User updateAvatar(Long userId, String avatarUrl) {
        User user = getUserById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        user.setAvatarUrl(avatarUrl);
        user.setUpdatedAt(LocalDateTime.now());
        user.setUpdatedBy(userId);
        
        return userRepository.save(user);
    }
    
    @Override
    public boolean isUsernameAvailable(String username, Long excludeUserId) {
        if (username == null || username.trim().isEmpty()) {
            return false;
        }
        
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            User existingUser = userOpt.get();
            return !existingUser.getId().equals(excludeUserId);
        }
        return true;
    }
    
    @Override
    public boolean isEmailAvailable(String email, Long excludeUserId) {
        if (email == null || email.trim().isEmpty()) {
            return true; // 空邮箱认为是可用的
        }
        
        Optional<User> userOpt = userRepository.findByEmail(email);
        if (userOpt.isPresent()) {
            User existingUser = userOpt.get();
            return !existingUser.getId().equals(excludeUserId);
        }
        return true;
    }
    
    @Override
    public boolean isMobileAvailable(String mobile, Long excludeUserId) {
        if (mobile == null || mobile.trim().isEmpty()) {
            return true; // 空手机号认为是可用的
        }
        
        Optional<User> userOpt = userRepository.findByMobile(mobile);
        if (userOpt.isPresent()) {
            User existingUser = userOpt.get();
            return !existingUser.getId().equals(excludeUserId);
        }
        return true;
    }
}
